﻿using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Eneta.Portal.Common;

namespace Eneta.Portal.WebStudio.Controls
{
    public class SchoolsControl : UserControl
    {
        protected Repeater SchoolsIterator;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            using (SPSite site = SPContext.Current.Site)
            {
                if (site == null)
                    return;
                using (SPWeb web = site.OpenWeb())
                {
                    if (web == null)
                        return;
                    if (web.HasList("Schools"))
                    {
                        SPList list = web.Lists["Schools"];
                        SPQuery query = new SPQuery();
                        query.Query = query.Query = "<Where><Eq><FieldRef Name='_ModerationStatus'/><Value Type='ModStat'>Kinnitatud</Value></Eq></Where>";
                        SPListItemCollection items = list.GetItems(query);
                        if (items != null)
                            if (items.Count > 0)
                            {
                                SchoolsIterator.DataSource = items;
                                SchoolsIterator.DataBind();
                            }
                    }

                }
            }
        }

        protected void SchoolsIterator_OnItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;
            SPListItem item = e.Item.DataItem as SPListItem;
            if (item == null)
                return;
            HtmlTableCell schoolName = (HtmlTableCell) e.Item.FindControl("name");
            HtmlTableCell teacher = (HtmlTableCell)e.Item.FindControl("teacher");
            HtmlTableCell url = (HtmlTableCell)e.Item.FindControl("url");
            if (item["SchoolName"] != null)
            {
                schoolName.InnerText = item["SchoolName"].ToString();
            } else
            {
                schoolName.InnerHtml = @"&nbsp;";
            }
            if (item["Teacher"]!= null)
            {
                teacher.InnerText = item["Teacher"].ToString();
            }
            else
            {
                teacher.InnerHtml = @"&nbsp;";
            }
            if (item["HomePage"]!= null)
            {
                SPFieldUrlValue value = new SPFieldUrlValue(item["HomePage"].ToString());
                if (value != null)
                {
                    url.InnerHtml = "<a href='" + value.Url + "'>" + value.Url + "</a>";
                }
            }
        }
    }
}
